from django.shortcuts import render

# Create your views here.
from jinja2 import Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig
from django.http import HttpResponse, StreamingHttpResponse
from pyecharts import options as opts
from pyecharts.charts import Bar

import xlwt

from firepark_admin import models

CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./statement/templates"))


def file_iterator(file_name, chunk_size=512):  # 用于形成二进制数据
    with open(file_name, 'rb') as f:
        while True:
            c = f.read(chunk_size)
            if c:
                yield c
            else:
                break


def index(request):
    Test_Data = models.all_records.objects.values()  # Test_Tab 中的所有数据对象

    DATA_title = list(Test_Data[0].keys())
    Line_len = len(Test_Data)
    Col_len = len(DATA_title)

    print("总数据：", Test_Data)

    print("数据字段名：", DATA_title)
    print("数据总行数：", Line_len)
    print("数据总列数：", Col_len)

    Excel_obj = xlwt.Workbook(encoding='utf-8')  # 创建要导出的 Excel 表格对象并指定编码
    Excel_tab = Excel_obj.add_sheet('sheet1')  # 创建 Excel 表(sheet1为Excel选项卡的表名，并非Excel文件名)
    DATA_title_ = ['id', '车牌号', '入库时间', '出库时间', '收费', '停车场编号', '是否注册']
    for T in range(0, Col_len):  # 列循环---便于写入 SQL字段[Ecel标题]
        Excel_tab.write(0, T, DATA_title_[T])
        print("标题索引列：", T, "当前列名：", DATA_title[T])
    for C in range(0, Line_len):  # 行循环---便于逐行写入数据
        DATA_line = dict(Test_Data[C])
        print("########################")
        print("当前行索引位：", C)
        print("当前数据库行数据：", DATA_line)

        for L in range(0, Col_len):  # 行循环嵌套列循环---便于写入每个字段/表格的数据
            DATA_field = DATA_title[L]
            DATA_value = DATA_line.get(DATA_field)
            if L == 2 or L == 3:
                DATA_value = DATA_value.strftime('%Y-%m-%d %H:%M:%S')
            Excel_tab.write(C + 1, L, DATA_value)

            print("当前列索引位：", L)
            print("当前列的字段名：", DATA_field)
            print("当前列写入的数据", DATA_value)

    Excel_obj.save('./Test_Excel.xls')
    response = StreamingHttpResponse(file_iterator('Test_Excel.xls'))  # 这里创建返回
    response['Content-Type'] = 'application/vnd.ms-excel'  # 注意格式
    response['Content-Disposition'] = 'attachment;filename="statement.xls"'  # 注意filename 这个是下载后的名字
    return response
    # bar = Bar()
    # bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
    # bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
    # bar.set_global_opts(title_opts=opts.TitleOpts(title="主标题", subtitle="副标题"))
    # return HttpResponse(bar.render_embed())
